<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\pay\addons;

require_once dirname ( __FILE__ ).'/wechat/lib/WxPay.Api.php';
require_once dirname ( __FILE__ ).'/wechat/example/WxPay.NativePay.php';
require_once dirname ( __FILE__ ).'/wechat/example/WxPay.JsApiPay.php';
require_once dirname ( __FILE__ ).'/wechat/example/WxPay.Config.php';

class Wechat
{
    /**
     * 二维码支付请求
     * @param  string $orderId    订单号
     * @param  string $title      订单标题
     * @param  float  $rmb        订单总金额
     * @param  string $notify_url 异步通知地址
     * @param  string $body       订单描述
     * @return array             
     */
    public static function qrCodePay($orderId, $title, $rmb, $notify_url, $body = "") 
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        if ($config->open() == 1) {
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($title);
            $input->SetAttach($body);
            $input->SetGoods_tag("a");
            $input->SetOut_trade_no($orderId);
            $input->SetTotal_fee($rmb * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 60*30));
            $input->SetNotify_url($notify_url);
            $input->SetTrade_type("NATIVE");
            $input->SetProduct_id("123456789");
            $notify = new \NativePay();
            $result = $notify->GetPayUrl($input);
            if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
                $url = index_url("pay/qrcode/index", ['data' => $result["code_url"], 'pay_type' => 'wechat']);
                return ['status' => 'success', 'message' => '二维码生成成功', 'data' => '<img src="'.$url.'" witdh="174" height="174" />'];
            } else {
                return ['status' => 'error', 'message' => '二维码生成失败', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '系统暂时关闭微信支付'];
        }
    }

    /**
     * 手机网站支付请求
     * @param  string $orderId    订单号
     * @param  string $title      订单标题
     * @param  float  $rmb        订单总金额
     * @param  string $notify_url 异步通知地址
     * @param  string $body       订单描述
     * @return string             
     */
    public static function wapPay($orderId, $title, $rmb, $notify_url, $body = "") 
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        if ($config->open() == 1) {
            $input  = new \WxPayUnifiedOrder();
            $input->SetBody($title);
            $input->SetAttach($body);
            $input->SetGoods_tag("a");
            $input->SetOut_trade_no($orderId);
            $input->SetTotal_fee($rmb * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 60*30));
            $input->SetNotify_url($notify_url);
            $input->SetTrade_type("MWEB");
            $input->SetProduct_id("123456789");
            $result = \WxPayApi::unifiedOrder($config, $input);
            if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
                return ['status' => 'success', 'message' => '生成成功', 'data' => $result['mweb_url']];
            } else {
                return ['status' => 'error', 'message' => '生成失败', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '系统暂时关闭微信支付'];
        }
    }

    /**
     * 小程序支付请求
     * @param  string $orderId    订单号
     * @param  string $title      订单标题
     * @param  float  $rmb        订单总金额
     * @param  string $notify_url 异步通知地址
     * @param  string $body       订单描述
     * @return string             
     */
    public static function jsPay($orderId, $title, $rmb, $notify_url, $body = "") 
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        if ($config->open() == 1) {
            //①、获取用户openid
            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();
            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($title);
            $input->SetAttach($body);
            $input->SetGoods_tag("a");
            $input->SetOut_trade_no($orderId);
            $input->SetTotal_fee($rmb * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 60*30));
            $input->SetNotify_url($notify_url);
            $input->SetTrade_type("JSAPI");
            $input->SetProduct_id("123456789");
            $input->SetOpenid($openId);
            $result = \WxPayApi::unifiedOrder($config, $input);
            if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
                $result['jsApiParameters'] = $tools->GetJsApiParameters($result);
                $result['editAddress']     = $tools->GetEditAddressParameters();
                return ['status' => 'success', 'message' => '生成成功', 'data' => $result];
            } else {
                return ['status' => 'info', 'message' => '生成失败', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '系统暂时关闭微信支付'];
        }
    }

    /**
     * 统一收单线下交易查询
     * @param  string $orderId    订单号
     * @return json   
     */
    public static function query($orderId)
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        $input = new \WxPayOrderQuery();
        $input->SetOut_trade_no($orderId);
        $result = \WxPayApi::orderQuery($config, $input);
        if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
            if ($result['trade_state'] === 'SUCCESS') {
                return ['status' => 'success', 'message' => '交易支付成功', 'data' => $result];
            } else {
                return ['status' => 'warning', 'message' => '交易查询成功', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '交易查询失败', 'data' => $result];
        }
    }

    /**
     * 统一收单交易退款
     * @param  string $orderId    订单号
     * @param  float  $rmb        退款金额
     * @param  float  $rmb        订单总金额
     * @param  string $reason     退款说明
     * @return json   
     */
    public static function refund($orderId, $rmb, $total, $reason = "")
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        if ($config->open() == 1) {
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($orderId);
            $input->SetTotal_fee($total * 100);
            $input->SetRefund_fee($rmb * 100);
            $input->SetOut_refund_no($orderId);
            $input->SetOp_user_id($config->GetMerchantId());
            $result = \WxPayApi::refund($config, $input);
            if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
                return ['status' => 'success', 'message' => '查询成功', 'data' => $result];
            } else {
                return ['status' => 'error', 'message' => '查询失败', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '系统暂时关闭微信支付'];
        }
    }

    /**
     * 统一收单线下交易退款查询
     * @param  string $orderId    订单号
     * @return json   
     */
    public static function refundQuery($orderId)
    {
        $config = new \WxPayConfig();
        if (empty($config->config)) {
            return ['status' => 'error', 'message' => '未配置微信支付功能'];
        }
        if ($config->open() == 1) {
            $input = new \WxPayRefundQuery();
            $input->SetOut_trade_no($orderId);
            $result = \WxPayApi::refundQuery($config, $input);
            if ($result['return_code'] == 'SUCCESS' && $result["result_code"] == "SUCCESS") {
                return ['status' => 'success', 'message' => '查询成功', 'data' => $result];
            } else {
                return ['status' => 'error', 'message' => '查询失败', 'data' => $result];
            }
        } else {
            return ['status' => 'error', 'message' => '系统暂时关闭微信支付'];
        }
    }
}